﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.Common.Json
{
    public static class Json4NetHelper
    {
        public static object Deserialize(string serializedObj)
        {
            var typeSeperatorIndex = serializedObj.IndexOf(TypeSeperator);
            var typeQualifiedName = serializedObj.Substring(0, typeSeperatorIndex);
            if (typeQualifiedName.StartsWith("\""))
            {
                typeQualifiedName = typeQualifiedName.Substring(1);
            }
            var type = Type.GetType(typeQualifiedName);
            var serialized = serializedObj.Substring(typeSeperatorIndex + 1);
            serialized = serialized.TrimEnd(new char[] { '"' });
            var options = new JsonSerializerSettings();
            options.Converters.Insert(0, new IsoDateTimeConverter());

            return JsonConvert.DeserializeObject(serialized, type, options);
        }

        public static T Deserialize<T>(string serializedObj)
        {
            return (T)Deserialize(serializedObj);
        }


        public static string Serialize2Format(object obj, Type type)
        {
            var serialized = obj.ToJsonString();

            return string.Format(
                "{0}{1}{2}",
                type.AssemblyQualifiedName,
                TypeSeperator,
                serialized
                );
        }

        public static string Serialize2Format(object obj)
        {
            return Serialize2Format(obj, obj.GetType());
        }


        private const char TypeSeperator = '|';
    }
}
